<?php

class NewsModel extends Model {
	
	public $definitions = array(
		"tables" => array("news")
	);
	
	public $order = "`news`.`date`";
	public $order_direction = "DESC";
	
	function shorten(&$news) {
	$max = 100;
		if (count($news)) {
			foreach ($news as &$n) {
				$n["body_short"] = preg_replace('/<img .*?>/',"",$n["body"]);
				if (strlen($n["body_short"])>$max) {
					$n["body_short"] = substr($n["body_short"],0, $max);
					
					$last = strrpos($n["body_short"],">")+1;
					if ($last>($max-10)) {
						$n["body_short"] = substr($n["body_short"],0,$last);
					}else{
						$tmp = substr($n["body_short"],0,$max);
						
						preg_match_all('/<([^\/][a-z1-9]*?)[\s>]/i',$tmp,$matches);
						$opened = $matches[1];
						
						preg_match_all('/<\/(.*?)>/',$tmp,$matches);
						$closed = $matches[1];
						
						$need_to_be_closed = array_reverse(array_diff($opened,$closed));
						
						foreach ($need_to_be_closed as $tag) {
							switch (strtolower($tag)) {
								case "hr":
								case "br":
								case "img":
									// check for attributes quotes
									$last = strrpos($tmp,"=\"")+2;
									if(strpos(substr($tmp,$last),"\"")===false) {
										$tmp .= "\"";
									}
									$tmp .= " />";
									break;
								default:
									$tmp .= "...";
									$tmp .= "</$tag>";
									break;
							}
						}
						$n["body_short"] = $tmp;
					}
					
				}
			}
		}
	}
	
	function find($fields="*",$filter=null,$limit=array(0,10)) {
		$news = parent::find($fields,$filter,$limit);
		$this->shorten($news);
		return $news;
	}
}

?>